<template>
  <div class="exam-container">
    <!-- 右上角倒计时和按钮 -->
    <div class="exam-header">
      <div class="timer">
        剩余时间：{{ minutes }}:{{ seconds }}
      </div>
      <div class="actions">
        <button @click="submitAnswers">提交</button>
        <button @click="handleClose">关闭</button>
      </div>
    </div>

    <!-- 考试题目 -->
    <h1>考试题目</h1>
    <div v-for="(exam, examIndex) in examList" :key="examIndex">
      <div v-for="(timu, timuIndex) in exam.timu_list" :key="timuIndex">
        <h3>{{ timu }}</h3>
        <ul>
          <li v-for="(option, optionIndex) in exam.xuanxiang_list[timuIndex]" :key="optionIndex">
            <label>
              <input
                type="radio"
                :name="'question' + examIndex + '_' + timuIndex"
                :value="option"
                v-model="userAnswers[examIndex][timuIndex]"
              />
              {{ option }}
            </label>
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>



<script>
import { getExam, updateClassScore } from "@/api/class/class_choose";
import Classes from "@/views/class/classes/index.vue";

export default {
  name: "Exam",
  data() {
    return {
      examList: [], // 初始化为空数组
      userAnswers: [], // 用户选择的答案
      timeLeft: 1800, // 30分钟倒计时，单位：秒
      timer: null, // 定时器
    };
  },
  computed: {
    // 计算分钟和秒数
    minutes() {
      return Math.floor(this.timeLeft / 60).toString().padStart(2, '0');
    },
    seconds() {
      return (this.timeLeft % 60).toString().padStart(2, '0');
    },
  },
  created() {
    this.getTest();
    this.startTimer(); // 启动倒计时
  },
  methods: {
    getTest() {
      const classId = this.$route.query.classId; // 获取路由参数中的 classId
      getExam(classId)
        .then((response) => {
          // 处理 examList 数据
          const processedExamList = response.map((exam) => {
            return {
              ...exam,
              xuanxiang_list: exam.xuanxiang_list.map((xuanxiang) => {
                if (typeof xuanxiang === "string") {
                  // 按照“；”分割字符串
                  return xuanxiang
                    .replace("选项：", "")
                    .split("；")
                    .slice(0, -1)
                    .map((item) => item.trim());
                }
                return xuanxiang;
              }),
            };
          });

          this.examList = processedExamList; // 将处理后的数据赋值给 examList
          // 初始化 userAnswers
          this.userAnswers = this.examList.map((exam) =>
            exam.timu_list.map(() => "")
          );
        })
        .catch((error) => {
          console.error("获取考试数据失败：", error);
        });
    },
    submitAnswers() {

      // 判断答案是否正确
      this.examList.forEach((exam, examIndex) => {
        exam.timu_list.forEach((timu, timuIndex) => {
          const userAnswer = this.userAnswers[examIndex][timuIndex].split(".")[0];
          console.log(userAnswer);
          const correctAnswer = exam.daan_list[timuIndex].split("：")[1]; // 提取正确答案
          console.log(correctAnswer);
          if (userAnswer === correctAnswer) {
            this.updateScore(2);
          } else {
            console.log("错误");
          }
        });
      });
      this.$modal.msgSuccess("提交成功");
      this.handleClose(); // 提交后自动关闭
    },
    updateScore(score) {
      const classId = this.$route.query.classId;
      updateClassScore(classId, score)
        .then((response) => {
          console.log("分数更新成功", response);
        })
        .catch((error) => {
          console.error("分数更新失败", error);
        });
    },
    /** 返回按钮操作 */
    handleClose() {
      const obj = { path: "/myClass/class_choose" };
      this.$tab.closeOpenPage(obj);
    },
    // 启动倒计时
    startTimer() {
      this.timer = setInterval(() => {
        if (this.timeLeft > 0) {
          this.timeLeft--;
        } else {
          clearInterval(this.timer);
          this.submitAnswers(); // 时间到自动提交
        }
      }, 1000);
    },
  },
  beforeDestroy() {
    clearInterval(this.timer); // 组件销毁时清除定时器
  },
};
</script>


<style scoped>
.exam-container {
  width: 90%;
  height: 90vh; /* 90% 的视口高度 */
  margin: 0 auto; /* 水平居中 */
  padding: 20px; /* 内边距 */
  box-sizing: border-box; /* 包含内边距和边框 */
  background-color: #f5f5f5; /* 背景色 */
  border: 1px solid #ddd; /* 边框 */
  border-radius: 8px; /* 圆角 */
  overflow-y: auto; /* 内容超出时显示滚动条 */
  position: relative;
}

.exam-header {
  position: absolute;
  top: 20px;
  right: 20px;
  display: flex;
  align-items: center;
  gap: 20px;
}

.timer {
  font-size: 18px;
  font-weight: bold;
  color: #ff4d4f; /* 红色倒计时 */
}

.actions {
  display: flex;
  gap: 10px;
}

.actions button {
  padding: 8px 16px;
  font-size: 14px;
  background-color: #007bff;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.actions button:hover {
  background-color: #0056b3;
}

ul {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

li {
  margin: 8px 0;
  display: block; /* 确保每个选项占一行 */
}

label {
  display: block;
  margin: 4px 0;
}

input[type="radio"] {
  margin-right: 8px;
}
</style>

